package com.rabbitmq.common.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * @author
 * @Describe 功能描述
 * @date
 */
@Slf4j(topic = "RabbitMqUtil")
public class RabbitMqUtil {

    /**
     * 连接工厂
     */
    private static ConnectionFactory connectionFactory;

    /**
     * 类加载时就进行初始化
     */
    static {
        connectionFactory = new ConnectionFactory();
        // 属性设置
        // 服务器主机
        connectionFactory.setHost("xxx");
        // 端口
        connectionFactory.setPort(5672);
        // 虚拟主机（各用户访问隔离）
        connectionFactory.setVirtualHost("v_xxx");
        // 用户名
        connectionFactory.setUsername("xxx");
        // 密码
        connectionFactory.setPassword("xxx");
    }

    /**
     *  获取连接
     */
    public static Connection getConn() {
        try {
            // 获取连接
            Connection connection = connectionFactory.newConnection();
            // 或者通过uri进行连接(amqp://username:password@hoste:port/virtualHost)
            // connectionFactory.setUri("amqp://username:password@hoste:port/virtualHost");

            return connection;
        } catch (Exception e) {
            log.error("[获取连接异常] getConn,", e);
            throw new RuntimeException("获取连接异常");
        }
    }

    /**
     * 销毁资源
     *
     * @param conn    连接
     * @param channel 通道
     */
    public static void close(Connection conn, Channel channel) {
        try {
            if (null != null) {
                conn.close();
            }
            if (null != channel) {
                channel.close();
            }
        } catch (Exception e) {
            log.error("关闭资源出错！", e);
        }
    }
}
